package cn.springbook.common.core.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;

/**
　* @description: Mybatis Plus自动插入配置
　* @param
　* @return  
　* @throws
　* @author caifenglin
　* @date 2021/7/2 17:31 
　*/
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    private static final String CREATE_TIME = "createTime";
    private static final String CREATE_USER = "createUser";
    private static final String UPDATE_TIME = "updateTime";
    private static final String UPDATE_USER = "updateUser";

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        boolean hasCreateTime = metaObject.hasGetter(CREATE_TIME);
        boolean hasCreateUser = metaObject.hasGetter(CREATE_USER) && ObjectUtils.isEmpty(getFieldValByName(CREATE_USER, metaObject));
        boolean hasUpdateTime = metaObject.hasGetter(UPDATE_TIME);
        boolean hasUpdateUser = metaObject.hasGetter(UPDATE_USER) && ObjectUtils.isEmpty(getFieldValByName(UPDATE_USER, metaObject));
        if (hasCreateTime) {
            this.strictInsertFill(metaObject, CREATE_TIME, LocalDateTime.class, LocalDateTime.now());
        }
        if (hasCreateUser) {
            // this.strictInsertFill(metaObject, CREATE_USER, String.class, "");
        }
        if (hasUpdateTime) {
            this.strictInsertFill(metaObject, UPDATE_TIME, LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐使用)
        }
        if (hasUpdateUser) {
            // this.strictInsertFill(metaObject, CREATE_USER, String.class, "");
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        boolean hasUpdateTime = metaObject.hasGetter(UPDATE_TIME);
        boolean hasUpdateUser = metaObject.hasGetter(UPDATE_USER);
        if (hasUpdateTime) {
            this.strictUpdateFill(metaObject, UPDATE_TIME, LocalDateTime.class, LocalDateTime.now());
        }
        if (hasUpdateUser) {
            // this.strictInsertFill(metaObject, hasUpdateUser, String.class, "");
        }
    }
}